<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // 通过Composer安装PHPMailer

header('Content-Type: application/json');

// 获取前端数据
$recipient = $_POST['recipient'] ?? '';
$subject = $_POST['subject'] ?? '';
$message = $_POST['message'] ?? '';

// 验证数据
if (empty($recipient) || empty($subject) || empty($message)) {
    echo json_encode(['success' => false, 'message' => '所有字段均为必填项']);
    exit;
}

// 使用Resend服务发送邮件
$mail = new PHPMailer(true);

try {
    // Resend SMTP配置
    $mail->isSMTP();
    $mail->Host = 'smtp.resend.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'resend'; // Resend固定用户名
    $mail->Password = 'YOUR_RESEND_API_KEY'; // 替换为你的Resend API Key
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port = 587;

    // 发件人设置（使用你的域名邮箱）
    $mail->setFrom('no-reply@yourdomain.com', 'Your Brand Name'); // 替换为你的域名
    $mail->addReplyTo('contact@yourdomain.com', 'Support Team'); // 替换为你的回复邮箱

    // 收件人
    $mail->addAddress($recipient);

    // 邮件内容
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = nl2br(htmlspecialchars($message)); // 安全处理
    $mail->AltBody = strip_tags($message); // 纯文本备用

    // 发送邮件
    $mail->send();
    echo json_encode(['success' => true, 'message' => '邮件已发送']);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => "发送失败: {$mail->ErrorInfo}"]);
}